//
//  ViewController.m
//  AddressBook
//
//  Created by dllo on 15/11/20.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "ViewController.h"
#import "AddVC.h"
#import "Person.h"
#import "CoreData.h"
#import "InfoVC.h"

@interface ViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>

@property(nonatomic, strong) UITableView *AddressTableView;
@property(nonatomic, strong) NSMutableArray *modelArr;
@property(nonatomic, strong) CoreData *manager;
@property(nonatomic, strong) UISearchBar *searchBar;
@property(nonatomic, strong) NSMutableArray *searchArr;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // tableView
    self.AddressTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.AddressTableView.delegate = self;
    self.AddressTableView.dataSource = self;
    [self.view addSubview:self.AddressTableView];
    [self.AddressTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"resue"];
    
    // barbutton
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemAdd) target:self action:@selector(Add:)];
    
    //
    self.manager = [CoreData defaults];
    
    //
    [self createData];
    
    //
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];
    self.AddressTableView.tableHeaderView = self.searchBar;
    self.searchBar.placeholder = @"搜索联系人";
    self.searchBar.delegate = self;
    
    // 遮盖层
    UIView *coverView = [[UIView alloc] initWithFrame:CGRectMake(0, 60, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    coverView.backgroundColor = [UIColor grayColor];
    coverView.alpha = 0.3;
    coverView.tag = 10000;
    [self.view addSubview:coverView];
    coverView.hidden = YES;
}

#pragma mark - createData
- (void)createData {
    
    //
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithValue:YES];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sex"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    self.modelArr = [NSMutableArray arrayWithArray:fetchedObjects];
}


#pragma mark - add
- (void)Add:(UIBarButtonItem *)button {
    AddVC *secVC = [[AddVC alloc] init];
    [self.navigationController pushViewController:secVC animated:YES];
}



#pragma mark - searchBar
// 开始编辑
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    self.searchBar.text = nil;
    [self.searchBar setShowsCancelButton:YES animated:YES];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    // 显示遮盖层
    UIView *coverView = (UIView *)[self.view viewWithTag:10000];
    coverView.hidden = NO;
    return YES;
}

// 取消按钮
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self.searchBar resignFirstResponder];
    [self.searchBar setShowsCancelButton:NO animated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    // 隐藏遮盖层
    UIView *coverView = (UIView *)[self.view viewWithTag:10000];
    coverView.hidden = YES;
    
    self.searchArr = nil;
    self.searchBar.text = nil;
    [self.AddressTableView reloadData];
    
}

// 点击空白取消搜索
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self searchBarCancelButtonClicked:self.searchBar];
}

// 实时监控
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    if (searchText != nil) {
        // 初始化
        self.searchArr = [NSMutableArray array];
        // 隐藏遮盖层
        UIView *coverView = (UIView *)[self.view viewWithTag:10000];
        coverView.hidden = YES;
        for (Person *per in self.modelArr) {
            // 搜索成功
            if ([per.name containsString:searchText] || [per.telephone containsString:searchText] || [per.sex containsString:searchText] || [per.number containsString:searchText] ||[per.qq containsString:searchText] || [per.birth containsString:searchText]) {
                [self.searchArr addObject:per];
                
                // 隐藏遮盖层
                UIView *coverView = (UIView *)[self.view viewWithTag:10000];
                coverView.hidden = YES;
            }
        }
        if (searchText.length != 0) {
            
            if (self.searchArr.count == 0) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"没有找到联系人" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                
                // 显示遮盖层
                UIView *coverView = (UIView *)[self.view viewWithTag:10000];
                coverView.hidden = NO;
            } else {
                [self.AddressTableView reloadData];
            }
        } else {
            // 显示遮盖层
            UIView *coverView = (UIView *)[self.view viewWithTag:10000];
            coverView.hidden = NO;
            
            self.searchArr = nil;
            [self.AddressTableView reloadData];
        }
    }
}



#pragma mark - edit
- (void)setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    
    [self.AddressTableView setEditing:editing animated:animated];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 删除一定要删除对应数据源的数据
        [self.modelArr removeObjectAtIndex:indexPath.row];
        
        [self.AddressTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
    
}



#pragma mark - tableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.searchArr.count == 0) {
        return self.modelArr.count;
    } else {
        return self.searchArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"resue"];
    
    if (self.searchArr.count == 0) {
        cell.textLabel.text = [self.modelArr[indexPath.row] name];
    } else {
        cell.textLabel.text = [self.searchArr[indexPath.row] name];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    InfoVC *info = [[InfoVC alloc] init];
    if (self.searchArr.count == 0) {
        info.nameStr = [self.modelArr[indexPath.row] name];
    } else {
        info.nameStr = [self.searchArr[indexPath.row] name];
    }
    [self.navigationController pushViewController:info animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - viewAppear
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self createData];
    [self.AddressTableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self searchBarCancelButtonClicked:self.searchBar];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

@end
